package com.jeesuite.bestpl.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import com.github.pagehelper.PageInfo;
import com.jeesuite.bestpl.dto.UserScore;
import com.jeesuite.bestpl.dto.UserScoreLog;
import com.jeesuite.bestpl.dto.WrapperResponseEntity;
import com.jeesuite.bestpl.exception.JeesuiteBaseException;
import com.jeesuite.bestpl.security.LoginUserInfo;
import com.jeesuite.bestpl.security.SecurityUtil;

@Service
public class UserScoreService {

	@Value("${userscoreApi.baseurl}")
	private String userScoreApiBaseUrl;
	@Autowired
	private RestTemplate restTemplate;
	
	public void addScore(int userId,int score,String remark){
		LoginUserInfo userInfo = SecurityUtil.getLoginUserInfo();
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("userName", userInfo.getName());
		params.put("score", score);
		params.put("remark", remark);
		restTemplate.postForObject(userScoreApiBaseUrl +"/user_score/add", params, String.class);
	}
	
	public UserScore findUserScoreByUserId(int userId){
		ParameterizedTypeReference<WrapperResponseEntity<UserScore>> arearesponseType = new ParameterizedTypeReference<WrapperResponseEntity<UserScore>>() {
		};
		WrapperResponseEntity<UserScore> responseEntity = restTemplate.exchange(userScoreApiBaseUrl +"/user_score/user/" + userId, HttpMethod.GET, null,arearesponseType).getBody();
		if(responseEntity.getCode() == 200){
			return responseEntity.getData();
		}
		throw new JeesuiteBaseException(responseEntity.getCode(), responseEntity.getMsg());
	}
	
	public PageInfo<UserScoreLog> pageQuery(@RequestBody Map<String, Object> params){
		ParameterizedTypeReference<WrapperResponseEntity<PageInfo<UserScoreLog>>> arearesponseType = new ParameterizedTypeReference<WrapperResponseEntity< PageInfo<UserScoreLog>>>() {
		};
		HttpEntity<Map> httpEntity = new HttpEntity<Map>(params);
		
		WrapperResponseEntity<PageInfo<UserScoreLog>> responseEntity = restTemplate.exchange(userScoreApiBaseUrl +"/user_score/page", HttpMethod.POST, httpEntity,arearesponseType).getBody();
		if(responseEntity.getCode() == 200){
			return responseEntity.getData();
		}
		throw new JeesuiteBaseException(responseEntity.getCode(), responseEntity.getMsg());
	}
}
